import { fileURLToPath, URL } from 'node:url'
import fs from 'node:fs'
import path from 'node:path'
import { defineConfig, type Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    devServerInfoPlugin(),
    vue(),
    vueJsx(),
    vueDevTools(),
  ],
  base: './', // 使用相对路径，这是保证静态资源正确加载的关键！
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  server: {
    cors: true,
    headers: {
      'Access-Control-Allow-Origin': '*', // 允许跨域
    },
  },
  optimizeDeps: {
    exclude: ['electron'], // 排除electron预构建，避免出现__dirname等Node.js变量未定义的错误
  },
})

// 写入开发服务器信息到项目根目录 .vite-dev-server.json
function devServerInfoPlugin(): Plugin {
  return {
    name: 'dev-server-info',
    apply: 'serve',
    configureServer(server) {
      try {
        const projectRoot = process.cwd();
        const infoPath = path.resolve(projectRoot, '.vite-dev-server.json');
        server.httpServer?.on('listening', () => {
          try {
            const addr = server.httpServer?.address();
            let port: number | undefined;
            if (addr && typeof addr === 'object') {
              port = addr.port;
            }
            const confPort = server.config.server.port as number | undefined;
            if (!port) port = confPort || 5173;
            const protocol = server.config.server.https ? 'https' : 'http';
            const host = (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
            const url = `${protocol}://${host}:${port}/`;
            const payload = { port, url, pid: process.pid, time: Date.now() };
            fs.writeFileSync(infoPath, JSON.stringify(payload), 'utf-8');
            console.log('[vite] dev server info written:', payload);
          } catch (e) {
            console.warn('[vite] failed to write dev server info:', e);
          }
        });
        server.httpServer?.on('close', () => {
          try {
            fs.rmSync(infoPath, { force: true });
          } catch {}
        });
      } catch (e) {
        console.warn('[vite] dev-server-info plugin init failed:', e);
      }
    },
  };
}
